package com.qf.gh.web.servlet;

import com.qf.gh.domain.Goods;
import com.qf.gh.domain.GoodsType;
import com.qf.gh.domain.User;
import com.qf.gh.service.GoodsService;
import com.qf.gh.service.GoodsTypeService;
import com.qf.gh.service.impl.GoodaServiceImpl;
import com.qf.gh.service.impl.GoodsTypeServiceImpl;
import com.qf.gh.utils.StrUtils;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@WebServlet("/adminGoods")
@MultipartConfig(maxFileSize = 1024*1024*5,maxRequestSize = 1024*1024*20)
public class AdminGoods extends BaseServlet{
    GoodsTypeService goodsTypeService=new GoodsTypeServiceImpl();
    GoodsService goodsService=new GoodaServiceImpl();

    public void searchGoodsType(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String username = request.getParameter("username");
        String level = request.getParameter("level");
        StringBuilder where=new StringBuilder("  WHERE 1=1  ");
        List<Object> parmas=new ArrayList<Object>();
        if(StrUtils.isNotEmpty(username)){
            where.append("  AND  name LIKE ?   ");
            parmas.add("%"+username+"%");
        }
        if(StrUtils.isNotEmpty(level)){
            where.append("  AND  level= ? ");
            parmas.add(Integer.parseInt(level));
        }
        List<GoodsType> goodsTypeList=goodsTypeService.findByName(where.toString(),parmas);
        request.getSession().setAttribute("goodsTypeList",goodsTypeList);
//        return "forward:/admin/showGoodsType.jsp";
    }

    public void searchGoods(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String username = request.getParameter("username");
        String pubdate = request.getParameter("pubdate");
        StringBuilder where=new StringBuilder("  WHERE 1=1  ");
        List<Object> parmas=new ArrayList<Object>();
        if(StrUtils.isNotEmpty(username)){
            where.append("  AND  name LIKE ?   ");
            parmas.add("%"+username+"%");
        }
        if(StrUtils.isNotEmpty(pubdate)){
            where.append("  AND  pubdate= ? ");
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            parmas.add(sdf.parse(pubdate));
        }
        List<Goods> goods=goodsService.findByName(where.toString(),parmas);
        request.getSession().setAttribute("goodsList",goods);
//        return "forward:/admin/showGoods.jsp";
    }

    public String getGoodsList(HttpServletRequest request, HttpServletResponse response)throws Exception{
        List<Goods> goods=goodsService.find();
        request.getSession().setAttribute("goodsList",goods);
        return "redirect:/admin/showGoods.jsp";
    }

    public String addGoods(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String name = request.getParameter("name");
        String typeid = request.getParameter("typeid");
        String pubdate = request.getParameter("pubdate");
        String price = request.getParameter("price");
        String star = request.getParameter("star");
        String intro = request.getParameter("intro");
        Part picture = request.getPart("picture");
        System.out.println(picture);
        Goods goods=new Goods();
        String basePath = this.getServletContext().getRealPath("WEB-INF/bookcovers");
        File dir=new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String dis = picture.getHeader("Content-Disposition");
        String filename = dis.substring(dis.lastIndexOf("filename=") + 10, dis.length() - 1);
        filename=filename.substring(filename.lastIndexOf("\\")+1);
        String exs = filename.substring(filename.lastIndexOf(".") + 1);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newFilename=uuid+"."+exs;
        if(!filename.equals("")){
            picture.write(basePath+File.separator+newFilename);
            picture.delete();
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        goods.setName(name);goods.setIntro(intro);goods.setPrice(Integer.parseInt(price));
        goods.setPubdate(sdf.parse(pubdate));goods.setStar(Integer.parseInt(star));
        goods.setPicture(newFilename);goods.setTypeid(Integer.parseInt(typeid));
        goodsService.insert(goods);
        List<Goods> goodss=goodsService.find();
        request.getSession().setAttribute("goodsList",goodss);
        return "redirect:/adminGoods?method=getGoodsList";
    }
    public String shouDoodsType(HttpServletRequest request, HttpServletResponse response)throws Exception{
        List<GoodsType> goodsTypes=goodsTypeService.selectAll();
        request.getSession().setAttribute("goodsTypeList",goodsTypes);
        return "redirect:/admin/showGoodsType.jsp";
     }
    public String addGoodsType(HttpServletRequest request, HttpServletResponse response)throws Exception{
        Object goodsTypeList = request.getSession().getAttribute("goodsTypeList");
        String goodsParent = request.getParameter("goodsParent");
        String typename = request.getParameter("typename");
        GoodsType goodsType=new GoodsType();
        goodsType.setName(typename);
        if(!"0".equalsIgnoreCase(goodsParent)) {
            goodsType.setParent(Integer.parseInt(goodsParent));
            GoodsType goodsType1 = goodsTypeService.selectById(Integer.parseInt(goodsParent));
            goodsType.setLevel(goodsType1.getLevel() + 1);
            goodsType.setParentName(goodsType.getName());
        }else{
            goodsType.setParent(0);
            goodsType.setLevel(1);
        }
        goodsTypeService.add(goodsType);
            List<GoodsType> goodsTypes=goodsTypeService.selectAll();
            request.getSession().setAttribute("goodsTypeList",goodsTypes);
        return "redirect:/admin/showGoodsType.jsp";
    }


    public void deleteGoodsType(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String id = request.getParameter("id");
        goodsTypeService.delete(Integer.parseInt(id));
//        return "forward:/adminGoods?method=shouDoodsType";

    }
    public String updateGoodsType(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String id = request.getParameter("id");
        GoodsType goodsType=goodsTypeService.selectById(Integer.parseInt(id));
        if(goodsType.getLevel()!=1){
            GoodsType goodsType1 = goodsTypeService.selectById(goodsType.getParent());
            goodsType.setParentName(goodsType1.getName());
        }
        request.setAttribute("goodsType",goodsType);
        return "forward:/admin/updateGoodsType.jsp";
    }

    public String updateGoodsType2(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String goodsParent = request.getParameter("goodsParent");
        String name = request.getParameter("typename");
        String level = request.getParameter("level");
        String id = request.getParameter("id");
        GoodsType goodsType=goodsTypeService.selectById(Integer.parseInt(id));
        GoodsType goodsType2=goodsTypeService.selectById(Integer.parseInt(goodsParent));
        GoodsType goodsType1=new GoodsType();
        goodsType1.setName(name);
        goodsType1.setId(Integer.parseInt(id));
        if(0==Integer.parseInt(goodsParent)){
            goodsType1.setLevel(1);goodsType1.setParent(0);
        }else if(goodsType.getId()==Integer.parseInt(goodsParent)){
            goodsType1.setLevel(goodsType.getLevel());goodsType1.setParent(goodsType.getParent());
        }else if(Integer.parseInt(goodsParent)==goodsType.getParent()){
            goodsType1.setLevel(goodsType.getLevel());goodsType1.setParent(goodsType.getParent());
        }else {
                goodsType1.setLevel(goodsType2.getLevel()+1);
                goodsType1.setParent(goodsType2.getId());
        }
        goodsTypeService.update(goodsType1);
        return "redirect:/adminGoods?method=shouDoodsType";
    }
        public String deleteGoods(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String id = request.getParameter("id");
        goodsService.delete(Integer.parseInt(id));
        return "redirect:/adminGoods?method=getGoodsList";
    }
    public String updateGoods(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String id = request.getParameter("id");
        Goods goods=goodsService.findById(Integer.parseInt(id));
        request.setAttribute("goods",goods);
        return "forward:/admin/updateGoods.jsp";
    }

    public String updateGoods1(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String name = request.getParameter("name");
        String typeid = request.getParameter("typeid");
        String pubdate = request.getParameter("pubdate");
        String price = request.getParameter("price");
        String star = request.getParameter("star");
        String intro = request.getParameter("intro");
        String id = request.getParameter("id");
        Part picture = request.getPart("picture");
        System.out.println(picture);
        Goods goods=new Goods();
        String basePath = this.getServletContext().getRealPath("WEB-INF/bookcovers");
        File dir=new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String dis = picture.getHeader("Content-Disposition");
        String filename = dis.substring(dis.lastIndexOf("filename=") + 10, dis.length() - 1);
        filename=filename.substring(filename.lastIndexOf("\\")+1);
        String exs = filename.substring(filename.lastIndexOf(".") + 1);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newFilename=uuid+"."+exs;
        if(!filename.equals("")){
            picture.write(basePath+File.separator+newFilename);
            picture.delete();
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        goods.setName(name);goods.setIntro(intro);goods.setPrice(Integer.parseInt(price));
        goods.setPubdate(sdf.parse(pubdate));goods.setStar(Integer.parseInt(star));
        goods.setPicture(newFilename);goods.setTypeid(Integer.parseInt(typeid));
        goodsService.update(goods,Integer.parseInt(id));
        return "redirect:/adminGoods?method=getGoodsList";
    }
}
